'use client'

import { useState } from 'react'
import { VmsCourse } from '@/types/Model'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { toast } from '@/hooks/use-toast'
import dynamic from 'next/dynamic'

// 动态导入 ReactQuill 以避免 SSR 问题
const ReactQuill = dynamic(() => import('react-quill'), { ssr: false })
import 'react-quill/dist/quill.snow.css'

interface CourseEditDialogProps {
  course: VmsCourse
  open: boolean
  onOpenChange: (open: boolean) => void
  onCourseUpdated: (updatedCourse: VmsCourse) => void
}

export default function CourseEditDialog({ 
  course, 
  open, 
  onOpenChange, 
  onCourseUpdated 
}: CourseEditDialogProps) {
  const [formData, setFormData] = useState<Partial<VmsCourse>>({
    id: course.id,
    title: course.title,
    description: course.description,
    content_description: course.content_description,
    is_free: course.is_free,
    max_participants: course.max_participants,
    access_password: course.access_password,
    status: course.status
  })
  const [loading, setLoading] = useState(false)

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? (value ? Number(value) : undefined) : value
    }))
  }

  const handleCheckboxChange = (name: string, checked: boolean) => {
    setFormData(prev => ({
      ...prev,
      [name]: checked
    }))
  }

  const handleSelectChange = (name: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleContentDescriptionChange = (content: string) => {
    setFormData(prev => ({
      ...prev,
      content_description: content
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/course/${course.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(formData)
      })
      
      if (!response.ok) {
        throw new Error('Failed to update course')
      }
      
      const updatedCourse = await response.json()
      onCourseUpdated(updatedCourse)
      onOpenChange(false)
      
      toast({
        title: '更新成功',
        description: '课程信息已更新',
      })
    } catch (error) {
      console.error('Error updating course:', error)
      toast({
        title: '更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>编辑课程</DialogTitle>
        </DialogHeader>
        
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-4">
            <div>
              <label htmlFor="title" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                课程标题 *
              </label>
              <Input
                id="title"
                name="title"
                type="text"
                value={formData.title}
                onChange={handleChange}
                className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                placeholder="输入课程标题"
                required
              />
            </div>
            
            <div>
              <label htmlFor="description" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                课程描述
              </label>
              <textarea
                id="description"
                name="description"
                value={formData.description}
                onChange={handleChange}
                className="w-full min-h-[50px] px-3 py-2 border border-slate-200 dark:border-slate-700 rounded-md focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-rose-500 bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
                placeholder="描述课程的内容和目标"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                课程内容简介（详细营销内容）
              </label>
              <div className="border border-slate-200 dark:border-slate-700 rounded-md overflow-hidden h-[250px]">
                <ReactQuill
                  value={formData.content_description}
                  onChange={handleContentDescriptionChange}
                  placeholder="输入详细的课程营销内容，支持富文本格式"
                  modules={{
                    toolbar: [
                      [{ 'header': [1, 2, 3, false] }],
                      ['bold', 'italic', 'underline', 'strike'],
                      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                      [{ 'color': [] }, { 'background': [] }],
                      ['link', 'image'],
                      ['clean']
                    ]
                  }}
                  formats={[
                    'header', 'bold', 'italic', 'underline', 'strike',
                    'list', 'bullet', 'color', 'background', 'link', 'image'
                  ]}
                  style={{
                    backgroundColor: 'white',
                    height: '250px'
                  }}
                />
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="status" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  课程状态
                </label>
                <Select value={formData.status} onValueChange={(value) => handleSelectChange('status', value)}>
                  <SelectTrigger className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800">
                    <SelectValue placeholder="选择状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="draft">草稿</SelectItem>
                    <SelectItem value="published">已发布</SelectItem>
                    <SelectItem value="archived">已归档</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <label htmlFor="max_participants" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  最大参与人数
                </label>
                <Input
                  id="max_participants"
                  name="max_participants"
                  type="number"
                  value={formData.max_participants || ''}
                  onChange={handleChange}
                  className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                  placeholder="不限制"
                  min="1"
                />
              </div>
            </div>
            
            <div>
              <label htmlFor="access_password" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                访问密码
              </label>
              <Input
                id="access_password"
                name="access_password"
                type="text"
                value={formData.access_password}
                onChange={handleChange}
                className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
                placeholder="留空表示无需密码"
              />
            </div>
            
            <div className="flex items-center space-x-2">
              <input
                id="is_free"
                name="is_free"
                type="checkbox"
                checked={formData.is_free}
                onChange={(e) => handleCheckboxChange('is_free', e.target.checked)}
                className="rounded border-slate-300 text-rose-600 focus:ring-rose-500"
              />
              <label htmlFor="is_free" className="text-sm font-medium text-slate-700 dark:text-slate-300">
                免费课程（学员可免费学习）
              </label>
            </div>
          </div>
          
          <div className="flex justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
            <Button 
              type="button" 
              variant="outline" 
              onClick={() => onOpenChange(false)}
              disabled={loading}
              className="border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800"
            >
              取消
            </Button>
            <Button 
              type="submit"
              disabled={loading}
              className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white border-0"
            >
              {loading ? '更新中...' : '更新课程'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}